<template>
    <!-- 操作按钮区 -->
   <div class="action-buttons">
     <el-button type="primary" @click="batchSaveDetails">添加</el-button>
     <!-- <el-button type="primary" @click="GetBYIdProductionPlanning(scope.row.pickingId)">编辑</el-button>
     <el-button @click="handleImport">导入</el-button> -->
   </div>
   
   <div>
     
       <div class="page-title">
           <h2>货物列表</h2>
       </div>
        <!-- 生产计划列表（仅展示序号列相关结构） -->
        <div class="table-container">
              <el-table :data="planList" stripe ref="tableRef">
                  <el-table-column type="selection"></el-table-column>
                  <el-table-column prop="goodsModelId" label="主键"></el-table-column>
                  <el-table-column prop="productName" label="产品名称"></el-table-column>
                  <el-table-column prop="productId" label="产品编号"></el-table-column>
                  <el-table-column prop="category" label="所属类别"></el-table-column>
                  <el-table-column prop="unit" label="单位"></el-table-column>
                  <el-table-column prop="specificationModel" label="规格型号"></el-table-column>
                  <el-table-column prop="unitPrice" label="单价"></el-table-column>
                  <el-table-column prop="productDescription" label="产品说明"></el-table-column>
                  <el-table-column prop="isEntity" label="是否为实体">
                    <template #default="scope">
                        {{ scope.row.isEntity ? '是' : '否' }}
                    </template>
                    </el-table-column>
                    <el-table-column prop="isTaxIncluded" label="是否含税">
                    <template #default="scope">
                        {{ scope.row.isTaxIncluded ? '是' : '否' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="isSelfMade" label="产品属性">
                    <template #default="scope">
                        {{ scope.row.isSelfMade === '1'? '自制' : scope.row.isSelfMade === '2'? '委外' : '委外' }}
                    </template>
                  </el-table-column>

                  <el-table-column prop="mainSupplier" label="主供应商"></el-table-column>
                  <el-table-column prop="safetyStock" label="安全库存"></el-table-column>
                  <el-table-column prop="inventoryLowerLimit" label="库存下限"></el-table-column>
                  <el-table-column prop="inventoryUpperLimit" label="库存上限"></el-table-column>
                  <el-table-column prop="lossRate" label="耗损率(%)"></el-table-column>
                  <el-table-column prop="productValidityDays" label="产品有效期（天）"></el-table-column>
                  <el-table-column prop="maintenanceCycle" label="养护周期"></el-table-column>
                  <el-table-column prop="barcodeImage" label="条形码图片"></el-table-column>
                  <el-table-column prop="right" label="操作">
                      <template #default="scope">
                          <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.goodsModelId)">编辑</el-button>
                          <el-button type="text" @click="DeleteProductionPlanning(scope.row.goodsModelId)">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
        </div>
        <div style="margin-top: 20px">
           <el-pagination
               v-model:current-page="page.pageindex"
               v-model:page-size="page.pageSize"
               :page-sizes="[4, 8, 12, 16]"
               :background="true"
               prev-text="上一页"
               next-text="下一页"
               layout="total, sizes, prev, pager, next, jumper"
               :total="total.totalCount"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
           />
       </div>
   </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import router from '@/router';
  import axios from 'axios';
  
  // 定义分页总数
  const total = ref({
      totalCount: 0,
      pageCount: 0,
  });
  // 定义分页对象
  const page = ref({
      pageindex: 1,
      pageSize: 4,
  });
  
  // 模拟生产计划列表数据
  const planList = ref([
      {
          "goodsModelId": '',
          "productName": "",
          "productId": "",
          "category": "",
          "unit": "",
          "specificationModel": "",
          "unitPrice": 0,
          "productDescription": "",
          "isEntity": true,
          "isTaxIncluded": true,
          "isSelfMade": 0,
          "mainSupplier": "",
          "safetyStock": 0,
          "inventoryLowerLimit": 0,
          "inventoryUpperLimit": 0,
          "lossRate": 0,
          "productValidityDays": 0,
          "maintenanceCycle": "",
          "barcodeImage": "",
          "isDel": true
      }
  ]);
  
  // 表格引用
  const tableRef = ref(null);
  
  // 全选状态
  const allChecked = ref(false);
  // 选中的 ID 列表
  const checkedIds = ref([]);
  
  const ShowMaterials = () => {
      axios.get("https://localhost:7090/api/Goods/GetGoods", {
          params: {
              pageindex: page.value.pageindex,
              pageSize: page.value.pageSize,
          }
      }).then((res) => {
          planList.value = res.data.data.result;
          console.log("显示数据", res.data.data);
  
          total.value.totalCount = res.data.data.totalCount;
          total.value.pageCount = res.data.data.pageCount;
          // 重置全选状态和选中的 ID 列表
          allChecked.value = false;
          checkedIds.value = [];
          console.log(res.data.data);
  
          // 数据校验
        //   const validationResult = validateTableData(planList.value);
          if (!validationResult.isValid) {
              ElMessage.error(validationResult.message);
          }
      }).catch((error) => {
          console.error('接口请求失败:', error);
        //   ElMessage.error('数据获取失败，请稍后重试');
      });
  };
  
  // 编辑跳转修改
  const GetBYIdProductionPlanning = (goodsModelId) => {
      router.push({
          name: 'UpdateGOODS',
          query: {
            goodsModelId: goodsModelId
          }
      }).catch((error) => {
          console.error('路由跳转错误:', error);
          ElMessage.error('跳转失败，请检查');
      });
      console.log(goodsModelId);
  };
  
  const batchSaveDetails = () => {
      router.push("/AddGoods");
  }
  
  // 单个删除功能
  // 删除单条记录
  const DeleteProductionPlanning = async (goodsModelId) => {
      try {
          const confirmResult = await ElMessageBox.confirm(
              '确认删除该条记录？',
              '提示',
              {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }
          );
          if (confirmResult === 'confirm') {
              const response = await axios.delete(
                  `https://localhost:7279/api/Goods/DelGoods`,
                  {
                      params: { GoodsModelId: goodsModelId.toString() }
                  }
              );
              if (response.data.code === 300) {
                  ElMessage.success('删除成功');
                  ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
              } else {
                  ElMessage.error(`删除失败：${response.data.message}`);
              }
          }
      } catch (error) {
          if (error !== 'cancel') {
              console.error('删除错误:', error);
              ElMessage.error('删除失败，请检查网络或联系管理员');
          }
      }
  };
  
  const handleSizeChange = (val) => {
      page.value.pageSize = val;
      ShowMaterials();
  };
  const handleCurrentChange = (val) => {
      page.value.pageindex = val;
      ShowMaterials();
  };
  
  // 校验函数
  const validateTableData = (data) => {
      const requiredFields = ['productName', 'category', 'unit', 'unitPrice'];
      const errorMessages = [];
      for (const item of data) {
          for (const field of requiredFields) {
              if (!item[field]) {
                  errorMessages.push(`记录中 ${field} 字段不能为空`);
              }
          }
          if (item.unitPrice < 0) {
              errorMessages.push('单价不能为负数');
          }
          if (item.safetyStock < 0) {
              errorMessages.push('安全库存不能为负数');
          }
          if (item.inventoryLowerLimit < 0) {
              errorMessages.push('库存下限不能为负数');
          }
          if (item.inventoryUpperLimit < 0) {
              errorMessages.push('库存上限不能为负数');
          }
          if (item.lossRate < 0) {
              errorMessages.push('耗损率不能为负数');
          }
          if (item.productValidityDays < 0) {
              errorMessages.push('产品有效期不能为负数');
          }
      }
      if (errorMessages.length > 0) {
          return { isValid: false, message: errorMessages.join('\n') };
      }
      return { isValid: true, message: '' };
  }
  
  onMounted(() => {
      ShowMaterials();
  })
  </script>
  
  <style scoped>
body {
  background-color: #f4f4f4;
  font-family: 'Arial', sans-serif;
}

.action-buttons {
  margin-bottom: 20px;
  text-align: left;
}

.custom-button {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

.custom-button:hover {
  background-color: #66b1ff;
}

.page-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.table-container {
  max-height: 400px; /* 固定表格最大高度 */
  overflow-y: auto; /* 超出高度显示滚动条 */
  margin-bottom: 20px; /* 为分页预留空间 */
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.el-table {
  width: 100%; /* 表格宽度占满容器 */
}

.el-table__header {
  background-color: #f4f4f4;
  font-weight: bold;
}

.el-table__body tr:hover {
  background-color: #fafafa;
}

.empty-table {
  text-align: center;
  padding: 20px;
  color: #999;
}

.action-button {
  color: #409eff;
  margin-right: 10px;
  transition: color 0.3s ease;
}

.action-button:hover {
  color: #66b1ff;
}
  </style>